import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException, TimeoutException, ElementNotInteractableException, ElementClickInterceptedException, WebDriverException
from time import sleep, time
import sys
import csv
import datetime
from PIL import Image,ImageEnhance

from chaojiying import Chaojiying_Client

Chaojiying_Client_username='guocdfeifei'
Chaojiying_Client_password='19870208'

mainAccounts = list()
subAccounts = list()
startTime = list()
giftName = ""
giftNum = 0

br1 = None
br2 = None
wait1 = None
wait2 = None
littleName = ''
mUn = ""
mPw = ""
sUn = ""
sPw = ""


def getAccount():
    global mainAccounts, subAccounts, giftName, giftNum
    with open('main.csv') as f:
        r = csv.reader(f)
        mainAccounts = list(r)

    with open('sub.csv') as f:
        r = csv.reader(f)
        subAccounts = list(r)

    for i in range(len(mainAccounts)):
        startTime.append(0)

    f = open("gift.txt")
    gift = f.read().split(",")
    giftName = gift[0]
    giftNum = int(gift[1])


timeout = 30


def initBrowser(which):
    global br1, br2, wait1, wait2
    profile = FirefoxProfile()
    profile.set_preference('network.proxy.type', 1)
    profile.set_preference('network.proxy.socks', '127.0.0.1')
    profile.set_preference('network.proxy.socks_port', 1080)
    profile.set_preference('network.proxy.ssl', '127.0.0.1')
    profile.set_preference('network.proxy.ssl_port', 1080)
    profile.set_preference('network.proxy.http', '127.0.0.1')
    profile.set_preference('network.proxy.http_port', 1080)
    if which == 1:
        br1 = webdriver.Firefox()
        br1.set_page_load_timeout(timeout)
        br1.set_script_timeout(timeout)
        wait1 = WebDriverWait(br1, timeout)
    elif which == 2:
        br2 = webdriver.Firefox()
        wait2 = WebDriverWait(br2, timeout)
        br2.set_page_load_timeout(timeout)
        br2.set_script_timeout(timeout)


def reOpenBr(which):
    if which == 1 and br1 != None:
        br1.quit()
    elif which == 2 and br2 != None:
        br2.quit()
    initBrowser(which)


def getVerifyCode(username, password):
    br = webdriver.Firefox()
    br.set_page_load_timeout(timeout)
    br.set_script_timeout(timeout)
    wait = WebDriverWait(br, timeout)
    try:
        br.get("http://mail.9fa.info:8080")
    except TimeoutException:
        pass

    wait.until(EC.presence_of_element_located(
        (By.ID, "rcmloginuser"))).send_keys(username)
    wait.until(EC.presence_of_element_located(
        (By.ID, "rcmloginpwd"))).send_keys(password)
    try:
        br.find_element_by_id("rcmloginsubmit").click()
    except TimeoutException:
        pass

    table = wait.until(EC.presence_of_element_located((By.ID, "messagelist")))
    table.find_elements_by_class_name("message")[0].click()


def login1(br, wait, un, pw):
    try:
        br.get("https://store.steampowered.com/login")
    except TimeoutException:
        # print("timeout")
        pass

    if br.current_url == "https://store.steampowered.com/":
        print("login already")
        return

    wait.until(EC.presence_of_element_located(
        (By.ID, 'input_username'))).send_keys(un)

    br.find_element_by_id('input_password').send_keys(pw)
    #todo 需要检测是否有验证码，如有需要接码
    print('需要检测是否有验证码，如有需要接码')
    dr = br.find_element_by_id('captcha_entry')
    # print(dr,'style',dr.value_of_css_property("display"))
    if dr and 'block'==dr.value_of_css_property("display"):
        #说明有验证码，截屏解析
        print('1')
        # 截图或验证码图片保存地址
        datetimenowTime = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')  # 现在

        import os
        if not os.path.isdir(r"./screenImg/"):
            os.makedirs(r"./screenImg/")
        screenImg = r"./screenImg/screenImg"+datetimenowTime+".png"
        # 浏览器页面截屏
        br.get_screenshot_as_file(screenImg)
        # 定位验证码位置及大小
        location = br.find_element_by_id('captcha_entry').location
        size = br.find_element_by_id('captcha_entry').size
        left = location['x']
        top = location['y']
        right = location['x'] + 206#size['width']
        bottom = location['y'] + 40#size['height']
        # 从文件读取截图，截取验证码位置再次保存
        img = Image.open(screenImg).crop((left, top, right, bottom))
        img = img.convert('L')  # 转换模式：L | RGB
        img = ImageEnhance.Contrast(img)  # 增强对比度
        img = img.enhance(2.0)  # 增加饱和度
        img.save(screenImg)
        chaojiying = Chaojiying_Client(Chaojiying_Client_username,Chaojiying_Client_password, '96001')  # 用户中心>>软件ID 生成一个替换 96001
        im = open(screenImg, 'rb').read()  # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
        aa = chaojiying.PostPic(im, 5000)
        print('aa',aa,aa['pic_str'])
        br.find_element_by_id('input_captcha').send_keys(aa['pic_str'])


    br.find_element_by_css_selector(
        '[class="btnv6_blue_hoverfade  btn_medium"]').click()

    #如果验证不通过，则重新登陆
    # print('error_display',br.find_element_by_id("error_display").value_of_css_property("display"))

    try:
        authcode = wait.until(
            EC.visibility_of_element_located((By.ID, "authcode")))
    except TimeoutException:
        # print('error_display', br.find_element_by_id("error_display").value_of_css_property("display"))
        if 'block'==br.find_element_by_id("error_display").value_of_css_property("display"):
            login1(br, wait, un, pw)
        else:
            return

    if sys.version > '3':
        a = input("continue:")
    else:
        a = raw_input("continue:")
    authcode.send_keys(a)
    authcode.send_keys(Keys.ENTER)
    try:
        wait.until(EC.element_to_be_clickable(
            (By.ID, "success_continue_btn"))).click()
    except TimeoutException:
        # print("timeout")
        pass


def login2(br, wait, un, pw):
    try:
        br.get("https://steamcommunity.com/login/")
    except TimeoutException:
        # print("timeout")
        pass

    wait.until(EC.presence_of_element_located(
        (By.ID, 'steamAccountName'))).send_keys(un)
    br.find_element_by_id(
        'steamPassword').send_keys(pw)
    br.find_element_by_id('SteamLogin').click()

    try:
        authcode = wait.until(
            EC.visibility_of_element_located((By.ID, "authcode")))
    except TimeoutException:
        return

    if sys.version > '3':
        a = input("continue:")
    else:
        a = raw_input("continue:")
    authcode.send_keys(a)
    authcode.send_keys(Keys.ENTER)

    try:
        wait.until(EC.element_to_be_clickable(
            (By.ID, "success_continue_btn"))).click()
    except TimeoutException:
        # print("timeout")
        pass


def rename():
    a = wait1.until(EC.presence_of_element_located(
        (By.CLASS_NAME, "user_avatar")))
    try:
        br1.get(a.get_attribute("href") + "edit")
    except TimeoutException:
        # print("timeout")
        pass

    e = wait1.until(EC.presence_of_element_located(
        (By.NAME, 'real_name')))
    e.clear()
    e.send_keys("1")

    try:
        br1.find_element_by_class_name("forum_manage_actions").find_element_by_css_selector(
            '[class="btn_green_white_innerfade btn_medium"]').click()
        # wait1.until(EC.element_to_be_clickable(
        #     (By.CSS_SELECTOR, '[class="btn_green_white_innerfade btn_medium"]'))).click()
    except TimeoutException:
        # print("timeout")
        pass

    try:
        wait1.until(EC.element_to_be_clickable(
            (By.CSS_SELECTOR, '[class="btn_grey_white_innerfade btn_small"]'))).click()
    except TimeoutException:
        # print("timeout")
        pass


def invite():
    global littleName
    try:
        br2.get(br1.current_url)
    except TimeoutException:
        # print("timeout")
        pass

    try:
        div = wait2.until(EC.presence_of_element_located(
            (By.CLASS_NAME, "profile_header_centered_persona")))
        littleName = div.find_element_by_class_name("actual_persona_name").text
        print(littleName)
        wait2.until(EC.element_to_be_clickable(
            (By.ID, 'btn_add_friend'))).click()
        return True
    except TimeoutException:
        print("oh no!")
        # print("timeout")
        return False


def acceptInvite():
    try:
        if br1.current_url.endswith("/"):
            br1.get(br1.current_url + 'home/invites')
        else:
            br1.get(br1.current_url + '/home/invites')
    except TimeoutException:
        #        print("timeout")
        pass

    try:
        br1.find_elements_by_class_name(
            "btnv6_white_transparent")[0].click()
    except IndexError:
        pass


def buyGift():
    wait2.until(EC.presence_of_element_located(
        (By.ID, "store_nav_search_term"))).send_keys(giftName)
    try:
        br2.find_element_by_id(
            "store_nav_search_term").send_keys(Keys.ENTER)
    except TimeoutException:
        #        print("timeout")
        pass

    try:
        wait2.until(EC.presence_of_all_elements_located(
            (By.CLASS_NAME, 'search_result_row')))[giftNum].click()
    except TimeoutException:
        #        print("timeout")
        pass

    try:
        wait2.until(EC.element_to_be_clickable(
            (By.CLASS_NAME, 'btnv6_green_white_innerfade'))).click()
    except TimeoutException:
        #        print("timeout")
        pass

    try:
        wait2.until(EC.element_to_be_clickable(
            (By.ID, 'btn_purchase_gift'))).click()
    except TimeoutException:
        #        print("timeout")
        pass

    try:
        br2.find_element_by_id('input_password').send_keys(mPw)
        br2.find_element_by_css_selector(
            '[class="btnv6_blue_hoverfade  btn_medium"]').click()
    except NoSuchElementException:
        try:
            br2.find_element_by_id(
                'steamPassword').send_keys(mPw)
            br2.find_element_by_id('SteamLogin').click()
        except (NoSuchElementException, TimeoutException):
            pass
    except TimeoutException:
        pass

    friends = wait2.until(EC.presence_of_element_located(
        (By.ID, "friends_chooser")))
    name = friends.find_elements_by_class_name("friend_name")
    for i in range(len(name)):
        if name[i].text == littleName:
            try:
                friends.find_elements_by_class_name(
                    "friend_block")[i].click()
                br2.find_elements_by_class_name(
                    "btnv6_green_white_innerfade")[0].click()
            except TimeoutException:
                # print("timeout")
                pass
            break
    try:
        wait2.until(EC.presence_of_element_located(
            (By.ID, "gift_recipient_name"))).send_keys("1")
        br2.find_element_by_id("gift_message_text").send_keys("1")
        br2.find_element_by_id("gift_signature").send_keys("1")
    except ElementNotInteractableException:
        return 1

    try:
        br2.find_element_by_id("submit_gift_note_btn").click()
    except TimeoutException:
        #        print("timeout")
        pass

    try:
        wait2.until(EC.element_to_be_clickable((By.ID, "accept_ssa"))).click()
    except TimeoutException:
        return 2
    try:
        br2.find_element_by_id("purchase_button_bottom").click()
    except TimeoutException:
        #        print("timeout")
        pass
    return 0


def acceptGift():
    try:
        br1.get("https://store.steampowered.com/gifts/")
    except TimeoutException:
     #        print("timeout")
        pass

    try:
        btns = wait1.until(EC.presence_of_all_elements_located(
            (By.CLASS_NAME, "btn_green_white_innerfade")))
    except TimeoutException:
        print('no btn found timeout')
        return

    for btn in btns:
        try:
            btn.click()
        except ElementClickInterceptedException:
            return

        sleep(2)
        try:
            wait1.until(EC.element_to_be_clickable(
                (By.CSS_SELECTOR, '[class="btn_green_white_innerfade btn_medium]'))).click()
        except TimeoutException:
            pass
        ll = br1.find_elements_by_class_name("newmodal_buttons")
        for l in ll:
            try:
                l.find_element_by_class_name(
                    "btn_grey_white_innerfade").click()
            except ElementClickInterceptedException:
                pass


if __name__ == '__main__':
    getAccount()
    i = 0
    j = 0
    lastJ = 0
    br2ReOpen = True
    exception = False
    while len(mainAccounts) > 0 and j < len(subAccounts):
        # main == i2, sub == j1
        if j - lastJ == 10:
            lastJ = j
            i += 1
            br2ReOpen = True
        if i >= len(mainAccounts):
            i = 0
        if br2ReOpen:
            reOpenBr(2)
            if not exception:
                while time() - startTime[i] < 4000:
                    print("Please wait, %d seconds left" %
                          (4000 - (int)(time() - startTime[i])))
                    sleep(300)
                startTime[i] = time()
        exception = False

        reOpenBr(1)
        mUn = mainAccounts[i][2].strip()
        mPw = mainAccounts[i][3].strip()
        sUn = subAccounts[j][2].strip()
        sPw = subAccounts[j][3].strip()
        littleName = sUn
        print("process:%s - %s\t%d - %d\t%d - %d" %
              (mUn, sUn, i, j, len(mainAccounts), len(subAccounts)))

        try:
            login1(br1, wait1, sUn, sPw)
            rename()

            if br2ReOpen:
                login2(br2, wait2, mUn, mPw)

            if invite():
                sleep(5)
                acceptInvite()

            if br2ReOpen:
                login1(br2, wait2, mUn, mPw)
                br2ReOpen = False
            else:
                try:
                    br2.get("https://store.steampowered.com/")
                except TimeoutException:
                    pass

            buyResult = buyGift()
            if buyResult == 1:
                print(sUn + " already had this gift!")
                j += 1
                continue
            elif buyResult == 2:
                print(mUn + " has no money!")
                del mainAccounts[i]
                del startTime[i]
                br2ReOpen = True
                continue
            elif buyResult == 0:
                pass

            sleep(5)
            acceptGift()
        except (NoSuchElementException, TimeoutException, WebDriverException) as e:
            print(e)
            br2ReOpen = True
            exception = True
            continue
        j += 1
    print('Over!')
